#!/usr/bin/env python
# coding=utf-8
"""
Description of this extension
"""

from collections import namedtuple
import inkex

class Linked2IncludedEffectExtension(inkex.EffectExtension):
    """Please rename this class, don't keep it unnamed"""
    def add_arguments(self, pars):
        pars.add_argument("--my_option", type=inkex.Boolean,\
            help="An example option, put your options here")

    def effect(self):
        pathNodes = self.document.xpath('//svg:image',namespaces=inkex.NSS)

        # Python 中 format 时对大括号的转义
        # https://blog.csdn.net/mingtiannihaoabc/article/details/103620145
        fullXLink = '{{{0}}}href'.format(inkex.NSS['xlink'])

        for cPathNode in pathNodes:
            fileLink = cPathNode.attrib[fullXLink]

            # self.msg(cPathNode.getparent().attrib['transform'])

            cPathNode.tag = '{{{0}}}g'.format(inkex.NSS['svg'])
            # del cPathNode.attrib[fullXLink]

            doc = inkex.elements.load_svg(fileLink)

            oWidth = 0
            oHeight = 0

            for node in doc.xpath('/svg:svg', namespaces=inkex.NSS):
                oWidth = float(inkex.units.convert_unit(node.get('width'), 'px'))
                oHeight = float(inkex.units.convert_unit(node.get('height'), 'px'))

            cPathNode.attrib['transform'] = 'translate({0},{1}) scale({2},{3})'.format(
                cPathNode.attrib['x'],
                cPathNode.attrib['y'],
                float(inkex.units.convert_unit(cPathNode.get('width'), 'px')) / oWidth,
                float(inkex.units.convert_unit(cPathNode.get('height'), 'px')) / oHeight
            )
            
            for foreignSVGNode in doc.xpath('/svg:svg', namespaces=inkex.NSS):
                # use doc.xpath('/svg:svg/*', namespaces=inkex.NSS) to select children of svg:svg node

                for symbolNode in foreignSVGNode.xpath('//svg:symbol', namespaces=inkex.NSS):
                    symbolNode.attrib['id'] += '-' + cPathNode.attrib['id']
                
                for useNode in foreignSVGNode.xpath('//svg:use', namespaces=inkex.NSS):
                    useNode.attrib[fullXLink] += '-' + cPathNode.attrib['id']

                cPathNode.append(foreignSVGNode)

            # textNodes = doc.xpath('//svg:text',namespaces=inkex.NSS)
            # for textNode in textNodes:
            #     self.msg(textNode.text)

            # with open(fileLink.replace('file:///',''), 'r') as f:
                # self.msg(f.read())

if __name__ == '__main__':
    Linked2IncludedEffectExtension().run()
